package juc.锁.LockSupport;

import java.util.concurrent.locks.LockSupport;

public class LockSupport_DEMO_2 {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();

        Thread.sleep(1000L);
        System.out.print("线程的阻塞原因竟是 " + LockSupport.getBlocker(thread).toString() + "\n");
        LockSupport.unpark(thread);
    }
}

class MyThread extends Thread {
    private int num = 0;

    @Override
    public void run() {
        while (true) {
            num++;
            System.out.println("num = " + num);

            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //根据条件，设置挂起当前线程
            if (num >= 10) {
                System.out.println("now, thread is parked!");
                LockSupport.parkNanos(new MyBlocker(20, "张三"), 3000000000L);//设置线程停止原因，超时3秒，自动复活
                num = 5;
            }
        }
    }
}

/**
 * 阻塞原因
 */
class MyBlocker {
    private int id;
    private String name;

    public MyBlocker(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "MyBlocker{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}